<?php
namespace Drupal\libsys\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Controller routines for qrcode login form.
 */
class Campusapp extends ControllerBase {
	public function Leave(Request $request) {

	// First let's fetch all the database settings
	$datasource=\Drupal::config('libsys.datasource');
	$keys=['host','port','database','username','password'];
	foreach($keys as $key) {
		if(empty($datasource->get($key))) return;
	}

	$result=['error_code'=>0];
	$xgh=json_decode($request->getContent())->xgh;

	try {
		// Use php-oci8 rather than pdo_oci, which is faster
		$conn=oci_connect($datasource->get('username'),$datasource->get('password'),
			sprintf("%s:%s/%s", $datasource->get('host'), $datasource->get('port'), $datasource->get('database')),'AL32UTF8'
		);
		if(!$conn) {
			$e=oci_error();
			throw new Exception($e['message'], $e['code']);
		}

		$sql=sprintf("select 1 from dual where exists(select * from lend_lst inner join reader_cert on lend_lst.cert_id=reader_cert.cert_id where reader_cert.redr_cert_id='%s')", $xgh);
		$stmt=oci_parse($conn, $sql);
		if(!$stmt) {
			$e=oci_error($stmt);
			throw new \Exception($e['message'], $e['code']);
		}
		$r=oci_execute($stmt, OCI_DEFAULT);
		if(!$r) {
			$e=oci_error($stmt);
			throw new \Exception($e['message'], $e['code']);
		}
		if(oci_fetch_row($stmt)==FALSE) {
			$result['data']['0']=['title'=>'图书资料清还','status' => 3];
			throw new \Exception();
		}
		$result['error_code']=0;

		$sql=sprintf("select M_title from marc inner join indi_acct on marc.marc_rec_no=indi_acct.marc_rec_no inner join lend_lst on lend_lst.prop_no=indi_acct.prop_no inner join reader_cert on lend_lst.cert_id=reader_cert.cert_id where reader_cert.redr_cert_id='%s'", $xgh);
		$stmt=oci_parse($conn, $sql);
		$r=oci_execute($stmt, OCI_DEFAULT);
		oci_fetch_all($stmt, $titles);
		$result['data']['0']=[
			'title'=>'图书资料清还',
			'status'=>2,
			'datum'=>implode(',',$titles['M_TITLE'])
		];

	} catch (\Exception $e) {
	} finally {
		if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);if(!empty($stmt))
			oci_free_statement($stmt);
		if(!empty($conn))
			oci_close($conn);
	}


	$response=new JsonResponse($result);
	$response->setEncodingOptions(JSON_UNESCAPED_UNICODE+JSON_PRETTY_PRINT );
	return $response;

}
}
?>
